package com.p2p.front.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.p2p.base.model.BaseUser;
import com.p2p.base.model.Money;
import com.p2p.base.page.PageVo;
import com.p2p.front.dal.dao.UserDao;
import com.p2p.front.dal.model.BorrowerPhoto;
import com.p2p.front.dal.model.IdCardInfo;
import com.p2p.front.dal.model.MemberPoint;
import com.p2p.front.dal.model.User;
import com.p2p.front.dal.model.UserCredits;
import com.p2p.front.enums.PhotoStatus;
import com.p2p.front.enums.PhotoType;
import com.p2p.front.service.BorrowerPhotoService;
import com.p2p.front.service.IdCardService;
import com.p2p.front.service.MemberPointService;
import com.p2p.front.service.TenderAmountSumService;
import com.p2p.front.service.UserRegisterService;
import com.p2p.front.service.UserService;
import com.p2p.trans.client.facade.AccountQueryFacade;
import com.p2p.trans.client.model.AccountVO;
import com.p2p.trans.client.result.AccountQueryResult;

@Service("userService")
public class UserServiceImpl implements UserService {

	@Resource
	private UserDao userDao;

	@Resource
	private BorrowerPhotoService borrowerPhotoService;

	@Resource
	private UserRegisterService userRegisterService;

	@Resource
	private IdCardService idCardService;
	
	@Resource
	private AccountQueryFacade remoteAccountQueryFacade;

	@Resource
	private MemberPointService memberPointService;

	
	@Resource
	private TenderAmountSumService tenderAmountSumService;
	
	@Override
	public User findById(String id) {
		return userDao.findById(id);
	}

	@Override
	public void update(User user) {
		userDao.update(user);
	}

	@Override
	public User searchUser(String search) {
		User user = userDao.checkMobileOrEmailExist(search, null);
		if (user == null) {
			user = userDao.checkMobileOrEmailExist(null, search);
		}
		if (user != null) {
			user = userDao.findById(user.getUid());
		}
		
		//userDao.search(search);
		return user;
	}
	
	@Override
	public List<User> searchUserList(String search) {
		/*User user = userDao.checkMobileOrEmailExist(search, null);
		if (user == null) {
			user = userDao.checkMobileOrEmailExist(null, search);
		}
		if (user != null) {
			user = userDao.findById(user.getUid());
		}*/
		
		List<User> userList = userDao.search(search);
		return userList;
	}
	
	@Override
	public PageVo searchUserListPage(String search,PageVo pageVo) {
		PageHelper.startPage(pageVo.getPageNum(), pageVo.getPageSize());
		List<User> userList = userDao.search(search);
		Page page = (Page)userList;
		pageVo.setList(userList);
		pageVo.setTotalCount((int)page.getTotal());
		pageVo.setPages(page.getPages());
		return pageVo;
	}

	public User findByUname(String uname) {
		return userDao.findByUname(uname);
	}

	@Override
	public User findByPhone(String mobilephone) {
		return userDao.findByPhone(mobilephone);
	}

	@Override
	public User findByEmail(String email) {
		return userDao.findByEmail(email);
	}

	@Override
	public void updateEmail(User user) {
		userDao.updateEmail(user);
	}

	@Override
	public Map<String, Object> get(Long id) {
		return userDao.get(id);
	}

	@Override
	public Map<String, Object> findAuthed(String idcard) {
		return userDao.findCard(idcard);
	}
	
	@Transactional
	public void authIdCard(IdCardInfo idCard,String fileName,BaseUser u){
		idCardService.saveIdCard(idCard);
		//userRegisterService.addCardId(idCard.getRealName(), idCard.getIdCard());
		if (StringUtils.isNotBlank(fileName)) {
			String[] fileNames = fileName.split(",");
			for (String name : fileNames) {
				BorrowerPhoto photo = new BorrowerPhoto();
				photo.setUid(u.getLongId());
				photo.setUrl(name);
				photo.setStatus(PhotoStatus.NORMAL.getCode());
				photo.setAddtime(new Date());
				photo.setType(PhotoType.IDCARD.getCode());
				borrowerPhotoService.save(photo);
			}
		}
	}

	@Override
	public Map<String,User> searchUserByIdList(List<String> idList) {
		Map<String,User> map = new HashMap<String,User>();
		List<User> userList = userDao.searchUserByIdList(idList);
		for(User user:userList){
			map.put(user.getUid(), user);
		}
		return map;
	}

	@Override
	public PageVo buildForExtraInfo(PageVo searchListPage) {
		List<String> accountNoList = new ArrayList<String>();
		List<String> userIdList = new ArrayList<String>();
		for (User user : (List<User>) searchListPage.getList()) {
			String accountNo = user.getAccountNo();
			if (StringUtils.isNotBlank(accountNo)) {
				accountNoList.add(accountNo);
			}
			String userId = user.getUid();
			userIdList.add(userId);
		}
		// 查询资金状态
		AccountQueryResult queryResult = remoteAccountQueryFacade
				.batchQueryAccountInfo(accountNoList);

		Map<String, MemberPoint> memberPointMap = memberPointService
				.queryByUserIdList(userIdList);
		
		Map<String,UserCredits>  totalTenderAmountMap = tenderAmountSumService.getUserTenderTatalAmount(userIdList);
		// Map<String,MemberPoint> memberPointMap = new
		// HashMap<String,MemberPoint>();
		List<Map<String, Object>> viewList = new ArrayList<Map<String, Object>>();
		if (queryResult.isSuccess()) {
			Map<String, AccountVO> accountVOmap = queryResult.getAccountVOMap();
			for (User user : (List<User>) searchListPage.getList()) {
				String accountNo = user.getAccountNo();
				String userId = user.getUid();
				Map<String, Object> usermodel = getViewModel(user,
						accountVOmap.get(accountNo), memberPointMap.get(userId),totalTenderAmountMap.get(userId));
				viewList.add(usermodel);
			}
		}
		searchListPage.setList(viewList);
		
		return searchListPage;
	}

	private Map<String, Object> getViewModel(User user, AccountVO accountVO,
			MemberPoint memberPoint,UserCredits userCredits) {
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("uid", user.getUid());
		model.put("uname", user.getUname());
		model.put("realname", user.getRealname());
		model.put("umobile", user.getUmobile());
		model.put("uemail", user.getUemail());
		model.put("accountNo", user.getAccountNo());
		if (accountVO != null) {
			model.put("balance", accountVO.getBalance().toString());
			model.put("freeze", accountVO.getFreezeAmount().toString());
			model.put("canUseBalance", accountVO.getCanUserBalance().toString());
		}
		if (memberPoint != null) {
			model.put("produceCumulative", memberPoint.getProduceCumulative());
			model.put("canUsedPoint", memberPoint.getCanUsedPoint());
			model.put("level", memberPoint.getLevel());
		}
		if(userCredits!=null){
			Money m = new Money(userCredits.getValue());
			model.put("totalTenderAmount", m.toString());
		}
		return model;

	}
}
